#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, thread, os, random, time, socket
import Ice

try:
    HOME = os.environ['ROBOTS']
except KeyError:
    print 'ROBOTS environment variable is not currently defined.'
    sys.exit(0)

SLICE = os.path.join(HOME, 'slice')
FILE = os.path.join(SLICE, 'Robots.ice')
Ice.loadSlice('--all -I/usr/share/slice', ['-I' + SLICE, FILE])

import Robots

PORT= 10001
TRANSITION = 1

class RobotI (Robots.Robot):

    def __init__ (self, address):
        self.__address = address
        self.__laser = False

        # Robot connection.
        self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.__socket.connect((address, PORT))
        except:
            print "Error connecting to %s" % (HOST)

        print 'Starting engines...'
        self.__socket.send('M   ')
        self.__socket.recv(256)

    def wait (self):
        time.sleep(TRANSITION)

    def move (self, to, sp, mmss, curr = None):
        print self.__address + ' moving!'
        self.__socket.send('M  z')
        self.__socket.recv(256)
        self.wait()

    def stop (self, curr = None):
        print self.__address + ' stopping!'
        self.__socket.send('5')
        self.__socket.recv(256)
        self.wait()

    def prowl (self, pos, curr = None):
        print self.__address + ' prowling!'

        self.move(Robots.Movement.Forward, 
                  Robots.Speed.SMedium,
                  random.Random().randint(50, 200))
        self.turn(Robots.Direction.DLeft, 2)
        self.move(Robots.Movement.Forward, 
                  Robots.Speed.SMedium,
                  random.Random().randint(50, 200))
        self.turn(Robots.Direction.DLeft, 2)
        self.move(Robots.Movement.Forward, 
                  Robots.Speed.SMedium,
                  random.Random().randint(50, 200))
        self.turn(Robots.Direction.DLeft, 2)
        self.move(Robots.Movement.Forward, 
                  Robots.Speed.SMedium,
                  random.Random().randint(50, 200))
        self.turn(Robots.Direction.DLeft, 2)
    
    def turn (self, dir, degrees, curr = None):
        print self.__address + ' turning!'

        for i in range (0, degrees):
            if dir == Robots.Direction.DLeft:
                self.__socket.send('0')
                self.__socket.recv(256)
            else:
                self.__socket.send('.')
                self.__socket.recv(256)
            self.wait()
    
    def capture (self, res, curr = None):
        pass

    def setLaser (self, on, curr = None):
        print self.__address + ' lassing!'
        self.__laser = on

        if on:
            self.__socket.send('l')
            self.__socket.recv(256)
        else:
            self.__socket.send('L')
            self.__socket.recv(256)

    def destroy (self, curr):
        self.__socket.send('5')
        self.__socket.recv(256)
        self.__socket.close()
        curr.adapter.remove(curr.id)
